<?php

namespace app\web\controller;

use app\common\controller\Frontend;
use app\common\model\customer\Customer;
use app\common\model\data\Voucher;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\sales\Checkout;
use app\common\model\sales\Retreat as retreatModel;
use app\common\model\sales\RetreatGoods;
use app\common\model\sales\Slip;
use think\Db;
use think\Exception;

class Retreat extends Frontend
{

    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $layout = '';


    public function index(){
        $model = new retreatModel;
        $status = $model->retreat_status();
        $storehouse_id = empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id'];
        $where['storehouse_id'] = $storehouse_id;
//        $where['storehouse_id'] = session('admin')['storehouse_id'];
        $list = Db::name('sales_retreat')
            ->field('s.id,s.number,explain,s.operator,s.company,retreat_num,actual_cost,h.name,c.company as ccompany,s.status')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->where($where)
            ->limit(0,10)
            ->order('s.id','DESC')
            ->select();
        $total = Db::name('sales_retreat')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->where($where)
            ->count();
        foreach ($list as &$v){
            $v['status_txt'] = $status[$v['status']];
        }

        $this->assign('total',$total);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function getretreat(){

        $page = input('page/d',1);
        $status = input('status/d',0);
        $pagesize = input('pagesize/d',10);
        $where = [];
        $storehouse_id = empty(session('admin')['storehouse_id'])?1:session('admin')['storehouse_id'];
        $where['storehouse_id'] = $storehouse_id;
//        $where['storehouse_id'] = session('admin')['storehouse_id'];
        if($status){
           $where['s.status'] = $status;
        }

        $model = new retreatModel;
        $status = $model->retreat_status();
        $list = Db::name('sales_retreat')
            ->field('s.id,s.number,explain,s.operator,s.company,retreat_num,actual_cost,h.name,c.company as ccompany,s.status')
            ->alias('s')
            ->join('storehouse h','s.storehouse_id = h.id')
            ->join('customer c','s.customer_id = c.id')
            ->limit($page*$pagesize,$pagesize)
            ->where($where)
            ->order('s.id','DESC')
            ->select();

//        $total = Db::name('sales_slip')
//            ->alias('s')
//            ->join('storehouse h','s.storehouse_id = h.id')
//            ->join('customer c','s.customer_id = c.id')
//            ->where($where)
//            ->count();
        foreach ($list as &$v){
            $v['status_txt'] = $status[$v['status']];
        }
        $this->success('','',$list);
    }

    public function detail(){
        $ids =input('ids/d',0);
        $model = new retreatModel();
        $row = $model->find($ids);
        if(empty($ids) || empty($row)){
            $this->error('查无数据');
        }
        if ($this->request->isAjax()) {
            if($row['status'] !=1){
                $this->error('状态异常');
            }
            $status = input('status/d',0);
            if(empty($status)){
                $this->error('异常');
            }
            Db::startTrans();
            try {
                $odata['status'] = $status;

                //驳回
                if($status == 4){
                    $RetreatGoods = new RetreatGoods;
                    $RetreatGoods->save(array('status'=>0),array('sales_retreat_id'=>$ids));
                    $type = 2;
                }
                $res = $model->save($odata,array('id'=>$ids));
                if($status == 2){
                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    $custrow = Customer::find($row['customer_id']);



                    Db::name('analysis')->insert(array(
                        'is_income'=>2,
                        'source'=>9,
                        'cost'=>$row['actual_cost'],
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'source_id' => $row['id'],
                        'obj_id' => $row['customer_id'],
                        'operator'=>session('admin')['nickname'],
                        'controller'=>'sales/retreat',
                        'settle_name'=>$custrow['company'],
                        'number'=>$row['number'],
                        'createtime'=>time(),
                        'storehouse_id' => $row['storehouse_id'],
                        'explain'=>$row['explain'],//摘要
                    ));
                    $type =1;
                }
                if(!$res){
                    Db::rollback();
                    throw new Exception('数据异常');
                }
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'sales/retreat',
                    'source_id'=>$ids,
                    'source'=>9,
                    'remark'=>'销售退货单',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));

                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'审核成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $Checkout = new Checkout;
        $crow = $Checkout->find($row['sales_checkout_id']);

        $list = Db::name('sales_retreat_goods')
            ->where(array('c.sales_retreat_id'=>$ids))
            ->alias('c')
            ->join('goods g','c.goods_id = g.id','LEFT')
            ->join('supplier_brands b','g.brands_id = b.id','LEFT')
            ->select();
        if(empty($crow['contacts']) || empty($crow['mobile'])){
            $crow = \app\common\model\customer\Customer::find($row['customer_id']);
            $contacts = $crow['contacts'];
            $mobile = $crow['mobile'];
            $address = $crow['address'];
        }else{
            $contacts = $crow['contacts'];
            $mobile = $crow['mobile'];
            $address = $crow['address'];
        }

        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('ids',$ids);
        $this->assign('contacts',$contacts);
        $this->assign('mobile',$mobile);
        $this->assign('address',$address);
        return $this->view->fetch();
    }
    //发货
    public function deliver(){
        exit;
        $ids =input('ids/d',0);
        $model = new checkoutModel();
        $row = $model->find($ids);
        if(empty($ids) || empty($row) ){
//        if(empty($ids) || empty($row) || $row['status'] !=2){
            $this->error('查无数据');
        }
        if($this->request->isAjax()){
            $img = input('img');
            $remark = input('remark');
            if(empty($img)){
                $this->error('图片不能为空');
            }
            if(file_exists(dirname(dirname(dirname(dirname(__FILE__)))).'/public'.$img)){
                $data = array(
                    'image'=>$img,
                    'remark'=>$remark,
                    'type'=>2,
                    'source_id'=>$ids,
                );
                //减少库存
                Db::startTrans();
                try {
                    $Slip = new Slip;
                    $ress = $Slip->checkstatus($row['sales_slip_id']);
                    if(!$ress){
                        throw new Exception('异常错误');
                    }

                    $plist = Db::name('sales_checkout_goods')->where(array('sales_checkout_id'=>$ids))->select();

                    foreach ($plist as $k=>$v){
                        //修改销售单商品状态
                        $sliprow = Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->find();
                        if($sliprow['goods_num'] == $v['goods_num']){ //出库完成
                            Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>3));
                        }else{
                            $num = Db::name('sales_checkout_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id'],'status'=>2))->sum('goods_num');//已经出库的商品数量
                            if($num+$v['goods_num'] == $sliprow['goods_num']){
                                Db::name('sales_goods')->where(array('sales_slip_id'=>$v['sales_slip_id'],'goods_id'=>$v['goods_id']))->update(array('status'=>3));
                            }
                        }
                        Db::name('sales_checkout_goods')->where(array('id'=>$v['id']))->update(array('status'=>2));

                        $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                        if($hgood['stock'] == 0){
                            throw new Exception('库存为0');
                        }
                        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                        Db::name('goods_stock_log')->insert(array(
                            'goods_id'=>$v['goods_id'],
                            'createtime'=>time(),
                            'number'=>$row['number'],
                            'type'=>'销售出库单',
                            'source'=>7,
                            'type_id'=>$row['id'],
                            'out_num'=>$v['goods_num'],
                            'before_num'=>$hgood['stock']+$v['goods_num'],
                            'now_num'=>$hgood['stock'],
                            'storehouse_id'=>$row['storehouse_id'],
                            'controller'=>'sales/checkout',
                            'admin_id'=>session('admin')['id'],
                            'group_id'=>$group['group_id'],
                            'company'=>$group['name'],
                            'operator'=>session('admin')['nickname'],
                            'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                            'bill_cost'=>($hgood['balance']/$hgood['stock'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                            'balance'=>$hgood['balance'], //记录的金额当前库存总额
                        ));
                        //减少库存

                        $GoodsHouseStock = new GoodsHouseStock;
                        $rr = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num']);
                        if(!$rr){
                            throw new Exception('库存异常');
                        }
                    }
                    $Voucher = new Voucher;
                    $Voucher->save($data);
                    $model = new checkoutModel();
                    $res = $model->save(array('status'=>3),array('id'=>$ids));
                    if($res){
                        Db::commit();
                        return array(
                            'code'=>1,
                            'msg'=>'发货成功',
                        );
                    }else{
                        throw new Exception('状态异常');
                    }
                }catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }else{
                $this->error('图片路径非法');
            }
//            dump();
            exit;
        }
        $this->assign('ids',$ids);
        return $this->view->fetch();
    }
    //到货
    public function arrive(){
        $ids =input('ids/d',0);
        $model = new checkoutModel();
        $row = $model->find($ids);
        if(empty($ids) || empty($row) || $row['status'] !=3){
            $this->error('查无数据');
        }
        $this->assign('ids',$ids);
        return $this->view->fetch();
    }
}
